<?php
if (!defined("MCTDESIGN")) die("#");
function temp_default()
{
    /*global $mysql, $tb_fix;
    $q = $mysql->query("select tpl_path from ".$tb_fix."_templates where tpl_default = 1");
    $r = $mysql->fetch_array($q);
    $template = $r['tpl_path'];
    return "./_temp/".$templatel;*/
    return "_temp/mctourist";
    
}
function get_title($table,$select,$where){
    global $anyDB,$tb_fix;
    $sql = "select $select from $table where $where limit 0,1";
    $q = $anyDB->query($sql);
    if($anyDB->numRows($q)>0){
        $r = $anyDB->getNext($q);
        return $r[$select];
    }
}
function subCutString($content, $limit, $chuoi=' '){
	$content = explode($chuoi,$content);
	$word_len = count($content);
	for($i=0; $i<$limit; $i++){
		$summary[$i] = $content[$i];
	}
	if($limit < $word_len){
		$summary = implode($chuoi, $summary).'...';
	}else{
		return implode($chuoi, $summary);
	}
	return $summary;
}
function is_valid_dir_name($input)
## Checks whether the directory- or filename is valid
	{
	if (strstr($input, "\\"))
		return FALSE;
	else
		if (strstr($input, "/"))
			return FALSE;
		else
			if (strstr($input, ":"))
				return FALSE;
			else
				if (strstr($input, "?"))
					return FALSE;
				else
					if (strstr($input, "*"))
						return FALSE;
					else
						if (strstr($input, "\""))
							return FALSE;
						else
							if (strstr($input, "<"))
								return FALSE;
							else
								if (strstr($input, ">"))
									return FALSE;
								else
									if (strstr($input, "|"))
										return FALSE;
                                        else
            								if (strstr($input, ","))
            									return FALSE;
            									else
            										return TRUE;
}
function convertText($text)
{
    $text = str_replace( 
    array(' ','%',"/","\\",'"','?','<','>',"#","^","`","'","=","!",":" ,",,","..","*","&","__"), 
    array('-','' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'-','' ,'-','' ,'' ,'' , "_" ,"" ,""), $text); 
    $chars = array("a","A","e","E","o","O","u","U","i","I","d", "D","y","Y"); 
    $uni[0] = array("á","à","ạ","ả","ã","â","ấ","ầ", "ậ","ẩ","ẫ","ă","ắ","ằ","ặ","ẳ"); 
    $uni[1] = array("Á","À","Ạ","Ả","Ã","Â","Ấ","Ầ", "Ậ","Ẩ","Ẫ","Ă","Ắ","Ằ","Ặ","Ẳ"); 
    $uni[2] = array("é","è","ẹ","ẻ","ẽ","ê","ế","ề" ,"ệ","ể","ễ"); 
    $uni[3] = array("É","È","Ẹ","Ẻ","Ẽ","Ê","Ế","Ề" ,"Ệ","Ể","Ễ"); 
    $uni[4] = array("ó","ò","ọ","ỏ","õ","ô","ố","ồ", "ộ","ổ","ỗ","ơ","ớ","ờ","ợ","ở"); 
    $uni[5] = array("Ó","Ò","Ọ","Ỏ","Õ","Ô","Ố","Ồ", "Ộ","Ổ","Ỗ","Ơ","Ớ","Ờ","Ợ","Ở"); 
    $uni[6] = array("ú","ù","ụ","ủ","ũ","ư","ứ","ừ", "ự","ử","ữ"); 
    $uni[7] = array("Ú","Ù","Ụ","Ủ","Ũ","Ư","Ứ","Ừ", "Ự","Ử","Ữ"); 
    $uni[8] = array("í","ì","ị","ỉ","ĩ"); 
    $uni[9] = array("Í","Ì","Ị","Ỉ","Ĩ"); 
    $uni[10] = array("đ"); 
    $uni[11] = array("Đ"); 
    $uni[12] = array("ý","ỳ","ỵ","ỷ","ỹ"); 
    $uni[13] = array("Ý","Ỳ","Ỵ","Ỷ","Ỹ"); 
    for($i=0; $i<=13; $i++) {
        $text = str_replace($uni[$i],$chars[$i],$text); 
    } 
    return strtolower($text); 
}
function get_config(){
    global $tb_fix,$anyDB;
    $sql = "select * from ".$tb_fix."_config";
    $q = $anyDB->query($sql);
    $r = $anyDB->getAll($q);
    return $r;
} 
function get_data($cf_name,$cf_value){
	global $mysql,$tb_fix;
	$q = $mysql->query("SELECT $cf_value FROM ".$tb_fix."_config WHERE config_name = '".$cf_name."'");
	$rs = $mysql->fetch_array($q);
	return $rs[$cf_value];
}

function vnDate($d) {
	$d = stripslashes($d);
	$d = str_replace( "Sunday","Chủ nhật",  $d );
	$d = str_replace( "Monday","Thứ hai",  $d );
	$d = str_replace( "Tuesday","Thứ ba",  $d );
	$d = str_replace( "Wednesday","Thứ tư",  $d );
	$d = str_replace( "Thursday","Thứ năm",  $d );
	$d = str_replace( "Friday","Thứ sáu",  $d );
	$d = str_replace( "Saturday","Thứ bảy",  $d );
	return $d;
}
function gmdates($input_date,$from=''){
	$zone=3600*7;
    if($from == 'static'){
        $out_date=gmdate("d-m-Y", $input_date + $zone);
    }else{
        $out_date=gmdate("d/m/Y H:i", $input_date + $zone);    
    }
	return $out_date;
}
function freeRTE_Preload($content) {
	// Strip newline characters.
	$content = str_replace(chr(10), " ", $content);
	$content = str_replace(chr(13), " ", $content);
	// Replace single quotes.
	$content = str_replace(chr(145), chr(39), $content);
	$content = str_replace(chr(146), chr(39), $content);
	// Return the result.
	return $content;
}

function mk_price($price){
    return number_format($price, 0, ',', '.');
    return $price;
}
function m_htmlchars($str) {
	return str_replace(
		array('&', '<', '>', '"', chr(92), chr(39)),
		array('&amp;', '&lt;', '&gt;', '&quot;', '&#92;', '&#39'),
		$str
	);
}
function htmlchars($str) {
	return str_replace(
		array('size="3"','Times New Roman, Times, serif',"font-size: small;","&#039",'&quot;','&amp;', '&lt;', '&gt;', '&quot;', '&#92;', '&#39'),
		array("",'',"","'",'"','&', '<', '>', '"', chr(92), chr(39)),
		$str
	);
}
function nbr($text) {
        return str_replace("\r\n", "<br>", $text);
}
function unbr($text) {
        return str_replace("<br>", "\r\n", $text);
}

function check_email($email) {
	if (strlen($email) == 0) return false;
	if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) return true;
	return false;
}
function fixquotes ($what = "") {
    $what = ereg_replace("'","''",$what);
    while (eregi("\\\\'", $what)) {
        $what = ereg_replace("\\\\'","'",$what);
    }
    return $what;
}
function get_title_product($id){
    global $anyDB,$tb_fix;
    $sql = "select pro_name from ".$tb_fix."_product where pro_id = $id";
    $q = $anyDB->query($sql);
    $r = $anyDB->getNext($q);
    return $r['pro_name'];
}
function show_thongke(){
    global $anyDB,$tb_fix;
    $NOW=time();
    $s_id = md5(session_id());
    $SID=$s_id;
    $IP = $_SERVER['REMOTE_ADDR'];
    $_date = gmdates(time(),'static');
    $data = array();
// update today
    $q = $anyDB->query("SELECT * FROM ".$tb_fix."_counter WHERE c_date='".$_date."' ORDER BY c_id ASC");
	$t = $anyDB->numRows($q);
	if ($t>0) {
        if(!$_SESSION['counter']){
            $_SESSION['counter'];
			$anyDB->query("UPDATE ".$tb_fix."_counter SET c_total=c_total+1 WHERE c_date='".$_date."'");
		}
	}
	else {
		$anyDB->query("INSERT INTO ".$tb_fix."_counter (c_date,c_total) VALUES ('".$_date."',1)");
	}    
    
//tong dm
    $q = $anyDB->query("SELECT count(tou_id) as tong_tour FROM ".$tb_fix."_tour");
    $r = $anyDB->getNext($q);
    $data['tong_tours'] = $r['tong_tour'];
// TONG SP    
    $q = $anyDB->query("SELECT count(hos_id) as tong_ks FROM ".$tb_fix."_hotels");
    $r = $anyDB->getNext($q);
    $data['tong_ks'] = $r['tong_ks'];
// TONG DON HANG
    $q = $anyDB->query("SELECT count(sid) as tong_news FROM ".$tb_fix."_news_post");
    $r = $anyDB->getNext($q);
    $data['tong_news'] = $r['tong_news'];    
// TONG DON HANG
    $q = $anyDB->query("SELECT count(logo_id) as tong_images FROM ".$tb_fix."_logos where logo_banner = 0");
    $r = $anyDB->getNext($q);
    $data['tong_images'] = $r['tong_images'];     
/* TOTAL */
	$query_total_visit = $anyDB->query("SELECT sum(c_total) AS Tong FROM ".$tb_fix."_counter");
	$lg = $anyDB->getNext($query_total_visit);
	$data['tong_truycap'] = number_format($lg["Tong"], 0, ',', ',');
/* DAY */
	$sql_select = $anyDB->query("SELECT * FROM ".$tb_fix."_counter WHERE c_date='".$_date."' ORDER BY c_id ASC");
	$lg = $anyDB->getNext($sql_select);
	$data['trong_ngay'] = "".$lg["c_total"]."";
/* ONLINE */
	$num = $anyDB->numRows($anyDB->query("SELECT s_id FROM ".$tb_fix."_online WHERE s_id = '".$SID."'"));
	if ($num == 0) $anyDB->query("INSERT INTO ".$tb_fix."_online (time, s_id, ip) VALUES ('".$NOW."', '".$SID."', '".$IP."')");
	else $anyDB->query("UPDATE ".$tb_fix."_online SET time='".$NOW."',ip='".$IP."' WHERE s_id='".$SID."'");
	$timeout = 60*1;
	$online = 0;
	$current_time = $NOW;
	$time_exit = $current_time - $timeout;
	$anyDB->query("DELETE FROM ".$tb_fix."_online WHERE time < ".$time_exit);
	$data['dang_online'] = $anyDB->numRows($anyDB->query("SELECT DISTINCT s_id FROM ".$tb_fix."_online WHERE s_id != ''"));
    
    return $data;
}
function permissions($_id="") {
	global $super_admin;
	$list = array();
	$list = explode(",",$super_admin);
	$end = count($list);
	$html = "Administrator";
	for($i = 0; $i < $end ; $i++) 
	{
		if ($_id == $list[$i]) {
			$html = "Super Administrator";
			break;
		}
	}
	return $html;
}
/* HÀM XUẤT File Extension*/
function findexts ($filename) 
 { 
 $filename = strtolower($filename) ; 
 $exts = split("[/\\.]", $filename) ; 
 $n = count($exts)-1; 
 $exts = $exts[$n]; 
 return $exts; 
 } 
function uploadIMG($filename="",$temp_filename="",$pathstore="news"){
	global $xtpl;
    //File Upload
    $sizelimit = "yes"; //Do you want a size limit, yes or no?
    $sizebytes = "1000000"; //size limit in bytes
    if (!empty($filename)) {
		/*$start = strpos($filename,".");
		$type = substr($filename,$start,strlen($filename));*/
        $type = findexts($filename);
		if ((strtolower($type)=="gif") || (strtolower($type)=="jpg")|| (strtolower($type)=="jpeg") || (strtolower($type)=="png") || (strtolower($type)=="swf")){
			if (($sizelimit == "yes") && (filesize($temp_filename) < $sizebytes)) {
                $str_key = "mctonline_";    
				$date=time();
                $filename = convertText($filename);
				$filename = $str_key.$date."_".$filename;
				$file_upload = "_uploads/".$pathstore."/".$filename;
				if ( !(copy($temp_filename, $file_upload)) ) die("Cannot upload files.");
			}
		}
	}
    return $file_upload;
}
      function txt_HTML($t=""){
               //$t = addslashes($t);
               $t = preg_replace("/&(?!#[0-9]+;)/s", '&amp;', $t );
               $t = str_replace( "<", "&lt;"  , $t );
               $t = str_replace( ">", "&gt;"  , $t );
               $t = str_replace( '"', "&quot;", $t );
               $t = str_replace( "'", '&#039;', $t );
               $t = str_replace( "&nbsp;",' ', $t );
              return $t;
      }

      function txt_unHTML($t=""){
               $t = stripslashes($t);
               //$t = nl2br($t);
               $t = str_replace( "&lt;","<",  $t );
               $t = str_replace( "&gt;",">",  $t );
               $t = str_replace( "&quot;",'"',  $t );//
               $t = str_replace( '\\&amp;amp;quot;', "", $t );
               $t = str_replace( "font-size: 10pt;",'', $t );
               $t = str_replace( ' face="Verdana" size="2"','', $t );
               $t = str_replace( "&nbsp;",' ', $t );
               $t = str_replace( "'",'&#039;', $t );
               return $t;
      }
       function clean_value($val) {
                if ($val == ""){
                    return "";
                }
                $val = str_replace( "&#032;", " ", $val );
                $val = str_replace( "&"            , "&amp;"         , $val );
                $val = str_replace( "<!--"         , "&#60;&#33;--"  , $val );
                $val = str_replace( "-->"          , "--&#62;"       , $val );
                $val = preg_replace( "/<script/i"  , "&#60;script"   , $val );
                $val = str_replace( ">"            , "&gt;"          , $val );
                $val = str_replace( "<"            , "&lt;"          , $val );
                $val = str_replace( "\""           , "&quot;"        , $val );
                $val = preg_replace( "/\n/"        , "<br />"        , $val ); // Convert literal newlines
                $val = preg_replace( "/\\\$/"      , "&#036;"        , $val );
                $val = preg_replace( "/\r/"        , ""              , $val ); // Remove literal carriage returns
                $val = str_replace( "!"            , "&#33;"         , $val );
                $val = str_replace( "'"            , "&#39;"         , $val ); // IMPORTANT: It helps to increase sql query safety.
                // Ensure unicode chars are OK
                $val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val );
                // Swop user inputted backslashes
                // $val = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $val );
                return $val;
       }
function Paginate($cat_code="",$cat_id="",$numRows, $maxRows, $pageNum=1, $pageVar="page", $class="pagelink"){
        $_html = "";
		$totalPages = ceil($numRows/$maxRows);
		$queryString = "";
		if (!empty($_SERVER['QUERY_STRING'])) {
		    $params = explode("&", $_SERVER['QUERY_STRING']);
		    $newParams = array();            
		    foreach ($params as $param) {
		             if (stristr($param, $pageVar) == false) {
				        array_push($newParams, $param);
		             }
		    }
		    if (count($newParams) != 0) {
		        $queryString = "?" . htmlentities(implode("&", $newParams));
		    }
		}
		$currentPage = $_SERVER['PHP_SELF'];
		if ($totalPages>= 1){
		    //$_html = "<strong>trang <font color='red'>".$pageNum."</font>/".$totalPages." </strong>";
		    $upper_limit = $pageNum + 10;
		    $lower_limit = $pageNum - 7;
                // trang dau + truoc
		        if ($pageNum > 1) {
		            if(($pageNum - 7)>0){
    		            //$first = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, 1);
                        $first = $cat_code."/".$cat_id."/index1.html";
    		            $_html .= "&nbsp;<a title=\"\" href='".$first."'>«« Trang đầu</a> &nbsp; ";
                    }
		            //$prev = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, max(0, $pageNum - 1));
                    $prev = $cat_code."/".$cat_id."/index".max(0, $pageNum - 1).".html";
		            $_html .= "&nbsp;<a title=\"\" href='".$prev."'>« </a> &nbsp; ";
		        }
                // danh sach trang
		        for($i = 1; $i < $totalPages+1; $i++){
		            $pageNo = $i;
		            if($i==$pageNum){
		               $_html .= "&nbsp;<span class=\"pagecur\"><b> ".$pageNo." </b></span>";
		            } 
		            else if($i!==$pageNum && $i<$upper_limit && $i>$lower_limit){
		               //$noLink = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, $i);
                       $noLink = $cat_code."/".$cat_id."/index".$i.".html";
		               $_html .= "&nbsp;<a title=\"Xem trang: ".$pageNo."\" href='".$noLink."'>".$pageNo."</a> ";
		            } 
		            else if(($i - $lower_limit)==0){
				         $_html .=  "&hellip;";
		             }
		        }
                // trang tiep + cuoi
		        if (($pageNum+1) <= $totalPages) {
		             //$next = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, min($totalPages, $pageNum + 1));
                     $next = $cat_code."/".$cat_id."/index".min($totalPages, $pageNum + 1).".html";
		             $_html .= " &nbsp; &nbsp;<a title=\"\" href='".$next."'> »</a> ";
		             if(($pageNum + 2)<=$totalPages){
						 //$last = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, $totalPages);
                         $last = $cat_code."/".$cat_id."/index".$totalPages.".html";
						 $_html .= " &nbsp; <a title=\"\" href='".$last."'>Trang cuối »»</a>";
		             }
		        }
		 }
		 return $_html;
}

function Paginate_Admin($numRows, $maxRows, $pageNum=1, $pageVar="page", $class="pagelink"){
        $_html = "";
		$totalPages = ceil($numRows/$maxRows);
		$queryString = "";
		if (!empty($_SERVER['QUERY_STRING'])) {
		    $params = explode("&", $_SERVER['QUERY_STRING']);
		    $newParams = array();
		    foreach ($params as $param) {
		             if (stristr($param, $pageVar) == false) {
				 array_push($newParams, $param);
		             }
		    }
		    if (count($newParams) != 0) {
		        $queryString = "?" . htmlentities(implode("&", $newParams));
		    }
		}
		$currentPage = $_SERVER['PHP_SELF'];
		if ($totalPages>= 1){
		    //$_html = "<strong>trang <font color='red'>".$pageNum."</font>/".$totalPages." </strong>";
		    $upper_limit = $pageNum + 6;
		    $lower_limit = $pageNum - 3;
		    if ($pageNum > 1) {
		        if(($pageNum - 3)>0){
		            $first = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, 1);
		            $_html .= "&nbsp;<li><a title=\"\" href='".$first."'>«« trang đầu</a> &nbsp; </li>";}
		            $prev = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, max(0, $pageNum - 1));
		            //$_html .= "&nbsp;<li><a title=\"\" href='".$prev."'>« trang trước</a> &nbsp; </li>";
		        }
		        for($i = 1; $i < $totalPages+1; $i++){
		            $pageNo = $i;
		            if($i==$pageNum){
		               $_html .= "&nbsp;<li class=\"current\"> <a href='#'>".$pageNo." </a></li>";
		            } 
		            else if($i!==$pageNum && $i<$upper_limit && $i>$lower_limit){
		               $noLink = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, $i);
		               $_html .= "&nbsp;<li><a title=\"View page: ".$pageNo."\" href='".$noLink."'>".$pageNo."</a> </li>";
		            } 
		            else if(($i - $lower_limit)==0){
				         $_html .=  "&hellip;";
		             }
		        }
		        if (($pageNum+1) <= $totalPages) {
		             $next = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, min($totalPages, $pageNum + 1));
		             $_html .= " &nbsp; &nbsp;<li><a title=\"\" href='".$next."'>trang tiếp »</a> </li>";
		             if(($pageNum + 2)<=$totalPages){
						 $last = sprintf("%s".$queryString."&".$pageVar."=%d", $currentPage, $totalPages);
						 $_html .= " &nbsp; <li><a title=\"\" href='".$last."'>trang cuối »»</a></li>";
		             }
		        }
		 }
		 return $_html;
}
/* lay ten don hang*/
function code_donhang(){
    return "DLC-";
}
function name_don_hang(){
    global $mysql,$tb_fix;
    $sql = "select dha_ten_dh from ".$tb_fix."_don_hang 
                                where dha_id = (select max(dha_id) from ".$tb_fix."_don_hang)";
    $query = $mysql->query($sql);
    if($mysql->num_rows($query)>0){
        $row=$mysql->fetch_array($query);
        $tendh=$row['dha_ten_dh'];                   
     }else{
        $tendh = '100000';
     }
     return $tendh;
}
// show cat_code, cat_id
function show_cat_code($id){
    global $tb_fix,$mysql;
    $sql = "select cat_code, cat_title from ".$tb_fix."_category where cat_id = $id";
    $q=$mysql->query($sql);
    $t=$mysql->num_rows($q);
    if($t > 0){
        $row=$mysql->fetch_array($q);
        if($row['cat_code'] == ""){
            $row['cat_code'] = convertText($row['cat_title']);
        }
    }
    return $row['cat_code'];
}
/* function hien thi block
/* param1: trang hien thi block (trangchu,danhmuc,sanpham...)
/* param2: cac vi tri hien thi tren trang (tren,trai,giua,phai,duoi)
/* param3: thu tu block tren trang (su dung neu co 1 block khac vi tri nam o giua 2 block cung vi tri)
/* param4: su dung khi chi muon lay 1 block bat ky nao do    
*/
function show_block($tranghienthi="",$vitri="",$thutu_block=1,$get_block=""){
    global $tb_fix,$anyDB;
    //thieu doan kiem tra vi tri co trong template mac dinh hay khong
    //viet sau
    if($get_block){
        $sql_block = " blo_id = '$get_block'";
    }else{
        $sql_block = " blo_index_position = '$tranghienthi' and tpl_position = '$vitri' and blo_position_order = '$thutu_block'";
    }
    $sql = "select blo_path,blo_file 
                from ".$tb_fix."_blocks 
            where $sql_block
                and blo_status = 1 
            order by blo_order asc";
    $q = $anyDB->query($sql);
    $t = $anyDB->numRows($q);
    if($t>0){
        $r = $anyDB->getAll();
        foreach($r as $val){
            $link_block = "./_blocks/".$val['blo_path']."/".$val['blo_file'];
            @require("$link_block");
        }
    }/*else{
        print "Không tìm thấy Block";
    } */         
}
/* function thu tu block
    hien thi toi da 10 thu tu
*/
function thutu_block(){
    $tt = array(1,2,3,4,5,6,7,8,9,10);
    return $tt;
}
/*
    function sep block hien thi o trang nao
*/
function show_index_vitri(){
    $i = array(
                "tatcatrang" => "Tất cả trang",
                "trangchu"  => "Trang chủ",
                "danhmuc"   => "Danh mục",
                "tintuc"    => "Tin tức",
                "sanpham"   => "Sản phẩm"
    );
    return $i;
}
/*
    function show cac vi tri co trong template mac dinh
*/
function show_vitri(){
    global $tb_fix,  $mysql;
    $sql = "select tpl_position from ".$tb_fix."_templates where tpl_default = 1";
    $r = $mysql->fetch_array($mysql->query($sql));
    $vtri = explode("|",$r['tpl_position']);
    return $vtri;
    
}
/*
    function hien thi nhom block de phan loai
*/
function show_block_group(){
    $group = array(
                    1 => "Nhóm chung",
                    2 => "Nhóm sản phẩm",
                    3 => "Nhóm tin tức",
                    4 => "Nhóm hình ảnh",
                    5 => "Nhóm quảng cáo & hỗ trợ",
                    6 => "Nhóm khác"
    );
    return $group;
}
/*
    hien thi block menu | site admin
*/
function show_block_menu(){
    global $tb_fix,$anyDB;
    $nhom = show_block_group();
    foreach($nhom as $k=>$v){
        $group_id = $k;
        $group[$k]['name'] = $v;
        $sql = "select * from ".$tb_fix."_blocks where blo_group = $group_id and blo_status = 1 order by blo_id desc";
        $q = $anyDB->query($sql);
        $t = $anyDB->numRows($q);
        if($t>0){
            $group[$k]['total']=$t;
            $group[$k]['hasChild'] = 1;
            $group[$k]['child'] = $anyDB->getAll($q);            
        }else{
            $group[$k]['total']=0;
        }
    }
    return $group;
}
// get mimetype
if( ! function_exists( 'get_file_mime_type' ) ) {
	function get_file_mime_type( $filename, $debug = false ) {
		if ( function_exists( 'finfo_open' ) && function_exists( 'finfo_file' ) && function_exists( 'finfo_close' ) ) {
			$fileinfo = finfo_open( FILEINFO_MIME );
			$mime_type = finfo_file( $fileinfo, $filename );
			finfo_close( $fileinfo );
			
			if ( ! empty( $mime_type ) ) {
				if ( true === $debug )
					return array( 'mime_type' => $mime_type, 'method' => 'fileinfo' );
				return $mime_type;
			}
		}
		if ( function_exists( 'mime_content_type' ) ) {
			$mime_type = mime_content_type( $filename );
			
			if ( ! empty( $mime_type ) ) {
				if ( true === $debug )
					return array( 'mime_type' => $mime_type, 'method' => 'mime_content_type' );
				return $mime_type;
			}
		}
		
		$mime_types = array(
        			 "hqx"		=> "application/mac-binhex40",
                     "doc"		=> "application/msword",
                     "dot"		=> "application/msword",
                     "bin"		=> "application/octet-stream",
                     "lha"		=> "application/octet-stream",
                     "lzh"		=> "application/octet-stream",
                     "exe"		=> "application/octet-stream",
                     "class"	=> "application/octet-stream",
                     "so"		=> "application/octet-stream",
                     "dll"		=> "application/octet-stream",
                     "pdf"		=> "application/pdf",
                     "ai"		=> "application/postscript",
                     "eps"		=> "application/postscript",
                     "ps"		=> "application/postscript",
                     "smi"		=> "application/smil",
                     "smil"		=> "application/smil",
                     "wbxml"	=> "application/vnd.wap.wbxml",
                     "wmlc"		=> "application/vnd.wap.wmlc",
                     "wmlsc"	=> "application/vnd.wap.wmlscriptc",
                     "xla"		=> "application/vnd.ms-excel",
                     "xls"		=> "application/vnd.ms-excel",
                     "xlt"		=> "application/vnd.ms-excel",
                     "ppt"		=> "application/vnd.ms-powerpoint",
                     "csh"		=> "application/x-csh",
                     "dcr"		=> "application/x-director",
                     "dir"		=> "application/x-director",
                     "dxr"		=> "application/x-director",
                     "spl"		=> "application/x-futuresplash",
                     "gtar"		=> "application/x-gtar",
                     "php"		=> "application/x-httpd-php",
                     "php3"		=> "application/x-httpd-php",
                     "php4"		=> "application/x-httpd-php",
                     "php5"		=> "application/x-httpd-php",
                     "phtml"	=> "application/x-httpd-php",
                     "js"		=> "application/x-javascript",
                     "sh"		=> "application/x-sh",
                     "swf"		=> "application/x-shockwave-flash",
                     "sit"		=> "application/x-stuffit",
                     "tar"		=> "application/x-tar",
                     "tcl"		=> "application/x-tcl",
                     "xhtml"	=> "application/xhtml+xml",
                     "xht"		=> "application/xhtml+xml",
                     "xhtml"	=> "application/xml",
                     "ent"		=> "application/xml-external-parsed-entity",
                     "dtd"		=> "application/xml-dtd",
                     "mod"		=> "application/xml-dtd",
                     "gz"		=> "application/x-gzip",
                     "zip"		=> "application/zip",
                		 "rar"		=> "application/rar",
                     "au"		=> "audio/basic",
                     "snd"		=> "audio/basic",
                     "mid"		=> "audio/midi",
                     "midi"		=> "audio/midi",
                     "kar"		=> "audio/midi",
                     "mp1"		=> "audio/mpeg",
                     "mp2"		=> "audio/mpeg",
                     "mp3"		=> "audio/mpeg",
                     "aif"		=> "audio/x-aiff",
                     "aiff"		=> "audio/x-aiff",
                     "m3u"		=> "audio/x-mpegurl",
                     "ram"		=> "audio/x-pn-realaudio",
                     "rm"		=> "audio/x-pn-realaudio",
                     "rpm"		=> "audio/x-pn-realaudio-plugin",
                     "ra"		=> "audio/x-realaudio",
                     "wav"		=> "audio/x-wav",
                     "bmp"		=> "image/bmp",
                     "gif"		=> "image/gif",
                     "jpeg"		=> "image/jpeg",
                     "jpg"		=> "image/jpeg",
                     "jpe"		=> "image/jpeg",
                     "png"		=> "image/png",
                     "tiff"		=> "image/tiff",
                     "tif"		=> "image/tif",
                     "wbmp"		=> "image/vnd.wap.wbmp",
                     "pnm"		=> "image/x-portable-anymap",
                     "pbm"		=> "image/x-portable-bitmap",
                     "pgm"		=> "image/x-portable-graymap",
                     "ppm"		=> "image/x-portable-pixmap",
                     "xbm"		=> "image/x-xbitmap",
                     "xpm"		=> "image/x-xpixmap",
                	 "ics"		=> "text/calendar",
                	 "ifb"		=> "text/calendar",
                     "css"		=> "text/css",
                     "html"		=> "text/html",
                     "htm"		=> "text/html",
                     "asc"		=> "text/plain",
                     "txt"		=> "text/plain",
                     "rtf"		=> "text/rtf",
                     "sgml"		=> "text/x-sgml",
                     "sgm"		=> "text/x-sgml",
                     "tsv"		=> "text/tab-seperated-values",
                     "wml"		=> "text/vnd.wap.wml",
                     "wmls"		=> "text/vnd.wap.wmlscript",
                     "xsl"		=> "text/xml",
                     "mpeg"		=> "video/mpeg",
                     "mpg"		=> "video/mpeg",
                     "mpe"		=> "video/mpeg",
                     "qt"		=> "video/quicktime",
                     "mov"		=> "video/quicktime",
                     "avi"		=> "video/x-msvideo",
                     "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                     "ppt" => "application/vnd.ms-powerpoint",
                     "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                     "xls" => "application/vnd.ms-excel",
                     "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
		);
		
		$ext = strtolower( array_pop( explode( '.', $filename ) ) );
		
		if ( ! empty( $mime_types[$ext] ) ) {
			if ( true === $debug )
				return array( 'mime_type' => $mime_types[$ext], 'method' => 'from_array' );
			return $mime_types[$ext];
		}
		
		if ( true === $debug )
			return array( 'mime_type' => 'application/octet-stream', 'method' => 'last_resort' );
		return 'application/octet-stream';
	}
}

/**
 * @author pavennt 
 * Hàm cắt chuỗi bằng từ 
 * 
 * 
 * 
 */ 
  function create_summary($text,$num)
 {

        //$text = strip_tags($cont);

        if(mb_strlen($text,'UTF-8') > $num){

            $endpos = mb_strpos($text,' ',$num,'UTF-8');
            $dots = '...';
            if(!$endpos){
                $endpos = mb_strlen($text,'UTF-8');
                $dots = '';
            }

        }else{
            $endpos = mb_strlen($text,'UTF-8');
            $dots ='';
        }                   
        return mb_substr($text,0,$endpos,'UTF-8').$dots;
}
/* format Price */
function priceFormat($num,$chasert)
{
     return preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/","$chasert",$num);
}
/*test function*/
function test($ver,$die=false){
    echo "<pre>";
    $a = print_r($ver);
    if($die){
        $a = $a.die();
    }
    return $a;
}
?>